#include "TimerQueue.h"
#include <assert.h>
#include "EventLoop.h"
#include "Timer.h"
#include "Log.h"

namespace dsth {

TimerQueue::TimerQueue(EventLoop* loop) 
    : loop_ptr_(loop),
    timerQueue_(::CreateTimerQueue()) {
    assert(loop_ptr_);
    if (timerQueue_ == NULL) {
        LOG_FATAL("CreateTimerQueue failed (%d)", ::GetLastError());
    }
}

TimerQueue::~TimerQueue() {
    for (TimerList::iterator it = timerList_.begin();
        it != timerList_.end(); ++it) {
        delete *it;
    }
    ::DeleteTimerQueue(timerQueue_);
}

TimerId TimerQueue::AddTimer(const TimerCallBack& callback, uint64_t duetime, uint64_t period) {
    Timer* timer = new Timer(callback, duetime, period, timerQueue_, loop_ptr_);
    HANDLE id = timer->GetTimerHandle();
    timerList_.push_back(timer);
    return id;
}

} // namespace
